package com.example.biji;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.FileProvider;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import static com.example.biji.NoteAdapter.getImageThumbnail;

public class EditActivity extends BaseActivity {

    EditText et;
    private String old_content = "";
    private String old_location = "";
    private String old_time = "";
    private int old_Tag = 1;
    private String old_Path = "";
    private int old_Flag = 0;
    private String new_Path = "";
    private int openMode = 0;
    private int tag = 1;
    private long id = 0;
    private String path = "";
    private Intent intent = new Intent();
    private boolean tagChange = false;
    private Toolbar myToolbar;
    private File phoneFile = null;
    private String selectedImagePath = "";
    private Context context = this;
    private String now_location = "";

    private int locationtemp = 0;
    //默认0关闭
    /*分割线，一下用1简写*/
    LocationClient mLocationClient;
    /*1*/



    private FloatingActionButton addOne, addTwo, addThree;    /*拍照按钮*/
    private ImageView c_img;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_layout);/*连接到edit_layout*/
        et = findViewById(R.id.et);
        Intent getIntent = getIntent();
        myToolbar = findViewById(R.id.myToolbar);
        openMode = getIntent.getIntExtra("mode", 0);

        /*1*/
        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(new MyLocationListener());

        setSupportActionBar(myToolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        addOne = (FloatingActionButton)findViewById(R.id.add_one);
        addTwo = (FloatingActionButton)findViewById(R.id.add_two);
        addThree = (FloatingActionButton)findViewById(R.id.add_three);
        c_img = findViewById(R.id.c_img);

        if (openMode == 3) {           /*mode为3代表再次点击记录，得到传过来的值*/
            id = getIntent.getLongExtra("id", 0);
            old_content = getIntent.getStringExtra("content");
            old_time = getIntent.getStringExtra("time");
            old_Tag = getIntent.getIntExtra("tag", 1);
            old_Flag= getIntent.getIntExtra("flag",1);
            old_location = getIntent.getStringExtra("location");

            new_Path =  old_Path = getIntent.getStringExtra("path");
            et.setText(old_content);

            if(old_Path.length() == 0) {
                c_img.setVisibility(View.GONE);
            } else {
                c_img.setImageBitmap((getImageThumbnail(old_Path,200, 200)));
                c_img.setVisibility(View.VISIBLE);
            }
            et.setSelection(old_content.length());/*光标位置设在最后*/
        }


        myToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                autoSetMessage();
                setResult(RESULT_OK,intent);
                finish();
                mLocationClient.stop();
            }
        });


        addOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent iimg = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                Uri uri;
                phoneFile = new File(Environment.getExternalStorageDirectory(),
                        "/camera_path/"+System.currentTimeMillis() + ".jpg");
                if (!phoneFile.getParentFile().exists()){
                    phoneFile.getParentFile().mkdirs();
                }
                if(Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                    uri = FileProvider.getUriForFile(EditActivity.this,
                            "com.mydomain.fileprovider", phoneFile);
                } else {
                    uri = Uri.fromFile(phoneFile);
                }

                iimg.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                startActivityForResult(iimg, 1);
                new_Path = phoneFile+"";
            }
        });

        addTwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent img = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                //设定结果返回
                startActivityForResult(img, 2);
            }
        });

        addThree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(locationtemp == 1) {
                    mLocationClient.stop();
                    locationtemp = 0;
                    addThree.setImageResource(R.drawable.ic_baseline_location_off_24);
                }else if(locationtemp == 0) {
                    mLocationClient.start();
                    requestLocation();
                    locationtemp = 1;
                    addThree.setImageResource(R.drawable.ic_baseline_location_on_24);
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 1) {
            Bitmap bitmap = BitmapFactory.decodeFile(phoneFile.getAbsolutePath());
            if(bitmap!=null) {
                c_img.setImageBitmap(bitmap);
                c_img.setVisibility(View.VISIBLE);
            }
        } else if(requestCode == 2 && data != null) {   /*要用==,而不能equals*/
            Uri selectedImage = data.getData();
            int width = 0;
            int height = 0;

            // imageView.setImageResource( R.drawable.tu2);
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImage, null,
                    null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            // 获取到图片的路径
            selectedImagePath = cursor.getString(columnIndex);

            Bitmap bm;
            bm = getImageThumbnail(selectedImagePath, 200, 200);
            if(bm!=null) {
                c_img.setImageBitmap(bm);
                c_img.setVisibility(View.VISIBLE);
            }
            new_Path = selectedImagePath;
        }
    }

    /*1*/

    private void requestLocation(){
        initLocation();
        mLocationClient.start();
    }

    private void initLocation(){
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd0911");
//    返回坐标类型，bd0911为百度标准
        option.setScanSpan(0);
//    发起请求定位的间隔，如果为0，则只执行一次，如果不为0，则最小为1000ms
        option.setOpenGps(true);
//    是否使用GPS，默认值为false
        option.setLocationNotify(false);
//    当GPS开启时按照1s/1次的频率输出gps结果，默认为false
        option.setIgnoreKillProcess(true);
//    可选，定位SDK内部的一个service，并且放到独立进程。
//    设置是否在stop时杀死这个进程，默认（建议不杀死），即ture
        option.setWifiCacheTimeOut(5 * 60 * 1000);
//    可选，如果设置了该接口，则首次启动定位时，会判断当前wifi是否超出有效期，如果超出有效期，会先重新扫描wifi再定位
        option.setEnableSimulateGps(false);
//    可选，设置是否过滤gps的仿真效果，默认需要，参数为false
        option.setIsNeedAddress(true);
//    返回国家城市等地理信息

        mLocationClient.setLocOption(option);
    }

    private class MyLocationListener extends BDAbstractLocationListener{

        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            StringBuilder currentPosition = new StringBuilder();
            if(bdLocation.getCountry() != null &&bdLocation.getProvince()!=null) {
                currentPosition.append(bdLocation.getCountry());
                currentPosition.append(bdLocation.getProvince());
                currentPosition.append(bdLocation.getCity());
                currentPosition.append(bdLocation.getDistrict());
                currentPosition.append(bdLocation.getTown());
                currentPosition.append(bdLocation.getStreet());
                now_location = currentPosition.toString();
            }else{
                now_location = "无法获取您的位置信息";
            }
        }
    }


    /*1*/

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.edit_menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        switch (item.getItemId()){
            case R.id.delete:
                new AlertDialog.Builder(EditActivity.this)
                        .setMessage("真的要删除吗,呜呜呜")
                        .setPositiveButton(android.R.string.yes,new DialogInterface.OnClickListener(){
                            @Override
                            public void onClick(DialogInterface dialog,int which){
                                if(openMode==4){
                                    intent.putExtra("mode",-1);
                                }
                                else{
                                    intent.putExtra("mode",2);
                                    intent.putExtra("id",id);
                                }
                                setResult(RESULT_OK,intent);
                                finish();
                            }
                        }).setNegativeButton(android.R.string.no,new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog,int which){
                        dialog.dismiss();
                    }
                }).create().show();
                break;

            case R.id.secret:
                new AlertDialog.Builder(EditActivity.this)
                        .setMessage("每点一下会改变这条笔记的保密状态哦！")
                        .setPositiveButton(android.R.string.yes,new DialogInterface.OnClickListener(){
                            @Override
                            public void onClick(DialogInterface dialog,int which){
                                if(old_Flag == 1) {
                                    old_Flag = 0;
                                }
                                else {
                                    old_Flag = 1;
                                }
                            }
                        }).setNegativeButton(android.R.string.no,new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog,int which){
                        dialog.dismiss();
                    }
                }).create().show();
                break;
        }

        return  super.onOptionsItemSelected(item);
    }





    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_HOME) {
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_BACK) {
            autoSetMessage();
            setResult(RESULT_OK, intent);    /*发送结果，并完成跳转*/
            finish();
            mLocationClient.stop();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    public String dateToStr() {  /*得到现在的时间，并转换为适当格式的字符串*/
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return simpleDateFormat.format(date);
    }

    public Boolean isNotEmpty(String s) {
        for (int i = s.length() - 1; i >= 0; i--) {
            char c = s.charAt(i);
            if (c != ' ' && c != '\n' && c != '\t') {
                return true;
            }
        }
        return false;
    }

    public void autoSetMessage() {
        if(openMode == 4) {
            if(!isNotEmpty(et.getText().toString()) && c_img.getVisibility() == View.GONE) {
                intent.putExtra("mode", -2);    /*笔记为空，不做事情*/
            } else {
                intent.putExtra("mode", 0);    /*新建一个记录*/
                intent.putExtra("content", et.getText().toString());
                intent.putExtra("time", dateToStr());
                intent.putExtra("tag", 1);
                intent.putExtra("location",now_location);
                intent.putExtra("path", phoneOrSelected(phoneFile+"",selectedImagePath));
                if(old_Flag == 1) {
                    intent.putExtra("flag", 1);
                }
                else{
                    intent.putExtra("flag", 0);
                }
            }
        } else {
            intent.putExtra("tag", 1);
            intent.putExtra("id", id);
            intent.putExtra("location",now_location);
            intent.putExtra("content", et.getText().toString());
            if(old_Flag == 1){
                intent.putExtra("flag", 1);
            }
            else{
                intent.putExtra("flag", 0);
            }
            if (et.getText().toString().equals(old_content) && old_Path == new_Path) {
                intent.putExtra("mode", -1);
                intent.putExtra("time", old_time);
                intent.putExtra("path",  old_Path);/*不是新建的，所以不能是phoneFile*/
            } else {
                intent.putExtra("mode", 1);          /*修改记录*/
                intent.putExtra("time", dateToStr());
                intent.putExtra("path",  new_Path);/*不是新建的，所以不能是phoneFile*/
            }
        }
    }


    public String phoneOrSelected(String phoneFile, String selectedImagePath) {
        if(phoneFile.equals("null")) {
            return selectedImagePath;
        } else {
            return phoneFile;
        }
    }
}


